﻿using System;
using System.Net;
using AgentListener.Model.Database;
using AgentListener.Model.Network;
using AgentListener.Mongo;
using Common;
using Common.Configuration;
using Common.Annotations;

namespace AgentListener.Controllers.Strategies
{
    internal class SyncStrategy : IRequestStrategy
    {
        [NotNull]
        private readonly IMongoProvider _provider;

        public SyncStrategy(IMongoProvider mongoProvider)
        {
            _provider = mongoProvider;
        }

        [CanBeNull]
        public ResponseInfo Process(RequestInfo data)
        {
            var syncData = JsonConvertWrapper.Deserialize<SyncData>(data.Query);

            if (syncData != null)
            {
                var agent = _provider.GetAgent(syncData.AgentId);

                ProcessAgent(agent, syncData);
                _provider.SaveAgent(agent);

                return new ResponseInfo(HttpStatusCode.InternalServerError, "OK");
            }

            return new ResponseInfo(HttpStatusCode.InternalServerError, "Wrong json message format");
        }

        private void ProcessAgent([NotNull] Agent agent, [NotNull] SyncData data)
        {
            if (agent == null) throw new ArgumentNullException("agent");
            if (data == null) throw new ArgumentNullException("data");

            if (agent.Status == AgentState.Download)
                CreateDefaultParameters(agent);

            agent.Status = AgentState.Up;
            agent.LastSyncDate = DateTime.Now;

            if (!_provider.AuthExists(data.AgentId))
                _provider.CreateAuth(data.SysId, agent.AgentId);
        }

        private void CreateDefaultParameters([NotNull] Agent agent)
        {
            if (agent == null) throw new ArgumentNullException("agent");

            //todo: вынести дефолты в отдельный конфиг??
        }
    }
}